﻿/*************************************************************************
 *  Copyright (C), 2017-2018, YangTao tech. Co., Ltd.
 *  FileName: ClientPanelScrp.cs
 *  Author: YangTao   Version: 1.0   Date: 11/28/2016
 *  Email:YangTao_Unity3D@163.com
 *  Version Description:
 *    
 *  File Description:
 *    
 *  Class List:
 *    <ID>           <name>             <description>
 *     1.         ClientPanelScrp             
 *  Function List:
 *    <ID>           <name>             <description>
 *     1.
 *  History:
 *    <ID>    <author>      <time>      <version>      <description>
 *     1.     YangTao     11/28/2016       1.0        Build this file.
 *************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.IO;

public class ClientPanelScrp : MonoBehaviour
{
    SocketClient m_client;
    /// <summary>消息显示</summary>
    public UILabel m_showText;
    /// <summary>消息输入</summary>
    public UIInput m_msgInput;
    /// <summary>分组名字</summary>
    public UIInput m_NameInput;
    /// <summary>连接按钮</summary>
    public UIButton m_connectBtn;
    /// <summary>发送按钮</summary>
    public UIButton m_sendBtn;
    /// <summary>Open按钮</summary>
    public UIButton m_openBtn;
    /// <summary>CreatButton按钮</summary>
    public UIButton m_creatGroupBtn;
    /// <summary>Group按钮</summary>
    public UIButton m_groupBtn;
    /// <summary>Creat按钮</summary>
    public UIButton m_creat;
    /// <summary>选择所有客户端按钮</summary>
    public UIButton m_allClientBtn;
    /// <summary>服务器按钮</summary>
    public UIButton m_serverBtn;
    /// <summary>是否连接</summary>
    static bool isConnect;
    /// <summary>显示消息链表</summary>
    public UITextList textList;
    /// <summary>已连接客户端</summary>
    public GameObject m_clientList;
    /// <summary>客户端Button</summary>
    public GameObject m_clientButton;
    /// <summary>客户端Grid</summary>
    public UIGrid m_clientGrid;
    /// <summary>分组客户端Grid</summary>
    public UIGrid m_groupClientGrid;
    /// <summary>选择分组客户端Grid</summary>
    public UIGrid m_selectClientGrid;
    /// <summary>分组Grid</summary>
    public UIGrid m_groupGrid;
    /// <summary>已连接客户端</summary>
    Dictionary<string, ClickClientButton> m_clientButtonDic;
    /// <summary>已连接客户端</summary>
    Dictionary<GameObject, string> m_clientButtonObjDic;
    /// <summary>已连接客户端</summary>
    Dictionary<string, GroupClickClientButton> m_groupClientButtonDic;
    /// <summary>已连接客户端</summary>
    Dictionary<GameObject, string> m_groupClientButtonObjDic;
    /// <summary>客户端组</summary>
    Dictionary<GameObject, List<string>> m_clientGroupDic;
    /// <summary>已选择客户端</summary>
    List<string> m_alreadySelectedCli;
    /// <summary>是否显示已连接客户端</summary>
    bool m_isShowClientList;
    /// <summary>已连接客户端列表</summary>
    public GameObject m_clientScroll;
    /// <summary>分组客户端Button</summary>
    public GameObject m_groupClientButton;
    /// <summary>分组列表</summary>
    public GameObject m_clientGroupScroll;
    /// <summary>分组界面</summary>
    public GameObject m_groupingPanel;
    /// <summary>分组界面内容</summary>
    public GameObject m_information;
    /// <summary>客户端分组下拉列表</summary>
    public GameObject ClientGroupList;
    /// <summary>客户端Button</summary>
    public List<GameObject> m_buttonList;
    /// <summary>分组已连接客户端列表</summary>
    public UIScrollView m_groupClientScroll;
    /// <summary>已选择客户端列表</summary>
    public UIScrollView m_selectClientScroll;
    /// <summary>是否添加客户端</summary>
    bool m_isAddClient;
    /// <summary>是否显示创建组界面</summary>
    bool m_isShowCreatGroup;
    /// <summary>是否显示分组界面</summary>
    bool m_isShowGroup;
    /// <summary>要添加的客户端</summary>
    List<string> m_addClientList;
    /// <summary>是否选择所有客户端</summary>
    bool m_isSelectAll;
    /// <summary>是否选择服务端</summary>
    bool m_isSelectServer;
    public UILabel m_clientIP;
    /// <summary>将要删除的客户端</summary>
    List<string> m_willDeletClient;

    string m_newContent;
    /// <summary>服务端IP</summary>
    string m_serverIP;

    void Start()
    {
        Init();
    }

    void Init()
    {
        UIEventListener.Get(m_connectBtn.gameObject).onClick += ConnectServer;
        UIEventListener.Get(m_sendBtn.gameObject).onClick += SendMessage;
        UIEventListener.Get(m_allClientBtn.gameObject).onClick += SelectAllClient;
        UIEventListener.Get(m_serverBtn.gameObject).onClick += SelectServer;
        UIEventListener.Get(m_creatGroupBtn.gameObject).onClick += OpenCreatGroup;
        UIEventListener.Get(m_groupBtn.gameObject).onClick += OpenGroup;
        UIEventListener.Get(m_creat.gameObject).onClick += CreatGroup;
        m_client = new SocketClient();
        m_client.Init();

        m_client.ReceiveMsgCallback += ReceiveMessage;
        m_client.IsConnectCallback += IsConnect;

        isConnect = false;
        m_client.AddClientCallback = AddClient;
        m_client.DeletClientCallback = DeletClient;

        m_clientButtonDic = new Dictionary<string, ClickClientButton>();
        m_clientButtonObjDic = new Dictionary<GameObject, string>();
        m_groupClientButtonDic = new Dictionary<string, GroupClickClientButton>();
        m_groupClientButtonObjDic = new Dictionary<GameObject, string>();
        m_clientGroupDic = new Dictionary<GameObject, List<string>>();
        m_alreadySelectedCli = new List<string>();
        m_isShowClientList = true;
        UIEventListener.Get(m_openBtn.gameObject).onClick += OpenClientList;
        m_isAddClient = false;
        m_addClientList = new List<string>();
        m_willDeletClient = new List<string>();
        m_newContent = "";
        m_isSelectAll = true;
        m_isSelectServer = true;
        m_isShowCreatGroup = true;
        m_isShowGroup = true;

        /*******************************获取服务端ip**********************************/
        //本地路径  
        var fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, "MyTxt.txt");
        FileInfo fInfo0 = new FileInfo(fileAddress);
        if (fInfo0.Exists)
        {
            StreamReader r = new StreamReader(fileAddress);
            m_serverIP = r.ReadToEnd();
        }
        m_client.m_serverIP = m_serverIP;
    }

    void Update()
    {
        ShowMsg();
        ClientButtonManage();
        CheckHeartBeat();
    }
    float timer;
    void CheckHeartBeat()
    {
        if (Time.time - timer > 5)
        {
            timer = Time.time;
            if (!m_client.m_isHeartBeat)
            {
                textList.Add("[FFEE00] Disconnect from server![-]");
                m_client.m_isHeartBeat = true;
            }
        }
    }

    void ShowMsg()
    {
        if (isConnect)
        {
            textList.Add("[8bddfc][-] Server is already connected!");
            m_clientIP.text = "Client " + m_client.m_clientIP;
            isConnect = false;
        }

        if (m_newContent != "")
        {
            textList.Add(m_newContent);
            m_newContent = "";
        }
    }

    /// <summary>客户端Button管理</summary>
    void ClientButtonManage()
    {
        if (m_isAddClient)
        {
            for (int i = 0; i < m_addClientList.Count; i++)
            {
                //Connected Client************************************************************************
                GameObject obj = NGUITools.AddChild(m_clientGrid.gameObject, m_clientButton);
                ClickClientButton ccb = obj.GetComponent<ClickClientButton>();

                ////处理网格的事务               
                m_clientGrid.repositionNow = true;

                //处理客户端Item事务
                ccb.m_clientIPLabel.text = m_addClientList[i];
                UIEventListener.Get(ccb.gameObject).onClick = ClickClientItem;

                m_clientButtonDic.Add(m_addClientList[i], ccb);
                m_clientButtonObjDic.Add(ccb.gameObject, m_addClientList[i]);

                //Grouping*********************************************************************************
                GameObject obj1 = NGUITools.AddChild(m_groupClientGrid.gameObject, m_groupClientButton);
                GroupClickClientButton gccb = obj1.GetComponent<GroupClickClientButton>();

                ////处理网格的事务        
                m_groupClientGrid.repositionNow = true;

                //处理客户端Item事务
                gccb.m_clientIPLabel.text = m_addClientList[i];
                UIEventListener.Get(gccb.gameObject).onClick = GroupClickClientItem;

                m_groupClientButtonDic.Add(m_addClientList[i], gccb);
                m_groupClientButtonObjDic.Add(gccb.gameObject, m_addClientList[i]);
            }
            m_isAddClient = false;
            m_addClientList.Clear();
        }
        if (m_willDeletClient.Count > 0)
        {
            for (int i = 0; i < m_willDeletClient.Count; i++)
            {
                //Connected Client************************************************************************
                GameObject item = m_clientButtonDic[m_willDeletClient[i]].gameObject;
                m_clientButtonDic.Remove(m_willDeletClient[i]);
                m_clientButtonObjDic.Remove(item);
                Destroy(item);
                m_clientGrid.repositionNow = true;

                //Grouping*********************************************************************************
                GameObject item1 = m_groupClientButtonDic[m_willDeletClient[i]].gameObject;

                m_groupClientButtonDic.Remove(m_willDeletClient[i]);
                m_groupClientButtonObjDic.Remove(item1);

                Destroy(item1);
                m_clientGrid.repositionNow = true;
                m_willDeletClient.RemoveAt(i);
            }
            m_clientGrid.repositionNow = true;
        }
    }

    /// <summary>点击客户端button</summary>
    void ClickClientItem(GameObject go)
    {
        string ip;
        if (m_clientButtonObjDic.TryGetValue(go, out ip))
        {
            ClickClientButton ccb;
            if (m_clientButtonDic.TryGetValue(ip, out ccb))
            {
                if (ccb.m_isAdd)
                {
                    m_alreadySelectedCli.Add(ccb.m_clientIPLabel.text);
                }
                else
                {
                    m_alreadySelectedCli.Remove(ccb.m_clientIPLabel.text);
                }
            }
        }
    }

    /// <summary>点击客户端button</summary>
    void GroupClickClientItem(GameObject go)
    {
        bool IsSelect = go.GetComponent<GroupClickClientButton>().m_isSelect;
        if (!IsSelect)
        {
            m_selectClientGrid.AddChild(go.transform);
            //go.GetComponent<UIDragScrollView>().scrollView = m_selectClientScroll;
            m_selectClientGrid.repositionNow = true;
            m_groupClientGrid.repositionNow = true;
            go.GetComponent<GroupClickClientButton>().m_isSelect = true;
        }
        else
        {
            m_groupClientGrid.AddChild(go.transform);
            //go.GetComponent<UIDragScrollView>().scrollView = m_groupClientScroll;
            m_selectClientGrid.repositionNow = true;
            m_groupClientGrid.repositionNow = true;
            go.GetComponent<GroupClickClientButton>().m_isSelect = false;
        }
    }

    /// <summary>
    /// 打开已连接客户端列表
    /// </summary>
    /// <param name="go"></param>
    void OpenClientList(GameObject go)
    {
        if (m_isShowClientList)
        {
            OpenClientList();
            if (!m_isShowCreatGroup)
                CloseCreatGroup();
        }

        else
        {
            CloseClientList();
        }
    }

    /// <summary>打开已连接客户端列表</summary>
    void OpenClientList()
    {
        MotionAestheticsScrp.AccLocalScaling(m_clientScroll, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_clientScroll, MABRANCH.SCALE).m_endCallback = ShowClient;
        m_openBtn.transform.Find("Label").GetComponent<UILabel>().text = "Close";
        m_isShowClientList = false;
    }

    /// <summary>关闭已连接客户端列表</summary>
    void CloseClientList()
    {
        m_clientList.gameObject.layer = LayerMask.NameToLayer("Default");
        MotionAestheticsScrp.AccLocalScaling(m_clientScroll, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_openBtn.transform.Find("Label").GetComponent<UILabel>().text = "Open";
        m_isShowClientList = true;
    }

    void ShowClient()
    {
        m_clientList.gameObject.layer = LayerMask.NameToLayer("UI");
    }

    /// <summary>
    /// 连接提示
    /// </summary>
    /// <param name="go"></param>
    void ConnectServer(GameObject go)
    {
        if (m_client.InitNetwork())
        {
            textList.Add("[8bddfc]Client connection...[-]");
        }
        else
            textList.Add("[8bddfc]Client is connected![-]");
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="go"></param>
    void SendMessage(GameObject go)
    {
        string sendString = m_msgInput.value;
        if (m_alreadySelectedCli.Count > 0 && sendString != "")
        {
            string ipStr = "";
            for (int i = 0; i < m_alreadySelectedCli.Count; i++)
            {
                string str = m_alreadySelectedCli[i];
                if (m_alreadySelectedCli[i] == m_serverIP + ":8888")
                    str = "Server";
                ipStr += str + " " + "||" + " ";
            }
            ipStr = ipStr.Remove(ipStr.Length - 3);
            string showInfo = "[00ffff]I[-]" + " " + "said to " + "[8bddfc]" + ipStr + "[-]" + ":" + sendString;
            textList.Add(showInfo);
            if (ipStr == "Server")
                m_client.SendContent(sendString);
            else
                m_client.SendContent(m_alreadySelectedCli, sendString);
            m_msgInput.value = "";//清空输入框内容
            for (int i = 0; i < m_alreadySelectedCli.Count; i++)
            {
                if (m_alreadySelectedCli[i] == m_serverIP + ":8888")
                {
                    m_serverBtn.GetComponentInChildren<UISprite>().color = Color.white;
                    m_isSelectServer = true;
                }
                else
                {
                    m_clientButtonDic[m_alreadySelectedCli[i]].m_buttonBg.GetComponent<UISprite>().color = Color.white;
                    m_clientButtonDic[m_alreadySelectedCli[i]].m_isAdd = false;
                }
            }
            //分组按钮颜色及bool重置
            IDictionaryEnumerator e = m_clientGroupDic.GetEnumerator();
            while (e.MoveNext())
            {
                GameObject groupButton;
                groupButton = (GameObject)e.Key;
                groupButton.GetComponent<ClickClientButton>().m_buttonBg.GetComponent<UISprite>().color = Color.white;
                groupButton.GetComponent<ClickClientButton>().m_isAdd = false;
            }

            m_alreadySelectedCli.Clear();
        }
    }

    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="sendfrom">发送方名称</param>
    /// <param name="content">消息体</param>
    void ReceiveMessage(string sendfrom, string content)
    {

        string name = "";
        if (sendfrom == m_serverIP + ":8888")
            name = "Server";
        else
            name = sendfrom;

        m_newContent = "[00ffff]" + name + "[-]" + ":" + content;
    }

    /// <summary>是否连接</summary>
    void IsConnect()
    {
        isConnect = true;
    }

    /// <summary>
    /// 添加已连接客户端至下拉列表
    /// </summary>
    /// <param name="str">连接客户端的IP</param>
    void AddClient(List<string> list)
    {
        if (list != null)
        {
            PreDefScrp.ListDeepCopy(list, out m_addClientList);
            m_isAddClient = true;
        }
    }

    /// <summary>
    /// 在下拉列表删除已连接客户端
    /// </summary>
    /// <param name="str">连接客户端的IP</param>
    void DeletClient(List<string> list)
    {
        m_willDeletClient = list;
        for (int i = 0; i < m_willDeletClient.Count; i++)
        {
            if (m_alreadySelectedCli.Contains(m_willDeletClient[i]))
            {
                m_alreadySelectedCli.Remove(m_willDeletClient[i]);
            }
        }
    }

    void SelectAllClient(GameObject obj)
    {
        if (m_isSelectAll)
        {
            IDictionaryEnumerator e = m_clientButtonDic.GetEnumerator();
            while (e.MoveNext())
            {
                ClickClientButton clientButton;
                clientButton = (ClickClientButton)e.Value;
                clientButton.m_buttonBg.GetComponent<UISprite>().color = Color.red;
                if (!m_alreadySelectedCli.Contains(clientButton.m_clientIPLabel.text))
                    m_alreadySelectedCli.Add(clientButton.m_clientIPLabel.text);
                clientButton.m_isAdd = true;
            }
            m_isSelectAll = false;
        }
        else
        {
            IDictionaryEnumerator e = m_clientButtonDic.GetEnumerator();
            while (e.MoveNext())
            {
                ClickClientButton clientButton;
                clientButton = (ClickClientButton)e.Value;
                clientButton.m_buttonBg.GetComponent<UISprite>().color = Color.white;
                m_alreadySelectedCli.Remove(clientButton.m_clientIPLabel.text);
                clientButton.m_isAdd = false;
            }
            m_isSelectAll = true;
        }
    }

    void SelectServer(GameObject obj)
    {
        if (m_isSelectServer)
        {
            m_alreadySelectedCli.Add(m_serverIP + ":8888");
            m_serverBtn.GetComponentInChildren<UISprite>().color = Color.red;
            m_isSelectServer = false;
        }
        else
        {
            m_alreadySelectedCli.Remove(m_serverIP + ":8888");
            m_serverBtn.GetComponentInChildren<UISprite>().color = Color.white;
            m_isSelectServer = true;
        }
    }

    /// <summary>打开创建组界面</summary>
    void OpenCreatGroup(GameObject obj)
    {
        if (m_isShowCreatGroup)
        {
            OpenCreatGroup();
        }

        else
        {
            CloseCreatGroup();
        }
    }

    /// <summary>打开创建分组界面</summary>
    void OpenCreatGroup()
    {
        SetButtonCollider(false);
        if (!m_isShowGroup)
            CloseGroup();
        if (!m_isShowClientList)
            CloseClientList();
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("Default");
        }
        m_information.GetComponent<UIPanel>().depth = 0;
        MotionAestheticsScrp.AccLocalScaling(m_groupingPanel, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_groupingPanel, MABRANCH.SCALE).m_endCallback = ShowInformatoin;
        m_isShowCreatGroup = false;
    }

    /// <summary>关闭创建分组界面</summary>
    void CloseCreatGroup()
    {
        SetButtonCollider(true);
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("Default");
        }
        m_information.GetComponent<UIPanel>().depth = 0;
        MotionAestheticsScrp.AccLocalScaling(m_groupingPanel, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_isShowCreatGroup = true;
    }

    /// <summary>展示创建组界面内信息</summary>
    void ShowInformatoin()
    {
        foreach (Transform tran in m_information.GetComponentsInChildren<Transform>())
        {
            tran.gameObject.layer = LayerMask.NameToLayer("UI");
        }
        m_information.GetComponent<UIPanel>().depth = 1;
    }

    /// <summary>打开分组</summary>
    void OpenGroup(GameObject obj)
    {
        if (m_isShowGroup)
        {
            OpenGroup();
            if (!m_isShowCreatGroup)
                CloseCreatGroup();
        }

        else
        {
            CloseGroup();
        }
    }

    /// <summary>打开分组</summary>
    void OpenGroup()
    {
        MotionAestheticsScrp.AccLocalScaling(m_clientGroupScroll, new Vector3(1, 0, 1), Vector3.one, 0.5f, 0, false);
        MotionAestheticsScrp.GetBranchScrp(m_clientGroupScroll, MABRANCH.SCALE).m_endCallback = ShowGroup;
        m_groupBtn.transform.Find("Label").GetComponent<UILabel>().text = "Close";
        m_isShowGroup = false;
    }

    /// <summary>关闭分组</summary>
    void CloseGroup()
    {
        ClientGroupList.gameObject.layer = LayerMask.NameToLayer("Default");
        MotionAestheticsScrp.AccLocalScaling(m_clientGroupScroll, Vector3.one, new Vector3(1, 0, 1), 0.5f, 0, false);
        m_groupBtn.transform.Find("Label").GetComponent<UILabel>().text = "Open";
        m_isShowGroup = true;
    }

    void ShowGroup()
    {
        ClientGroupList.gameObject.layer = LayerMask.NameToLayer("UI");
    }

    /// <summary>创建分组</summary>
    void CreatGroup(GameObject obj)
    {
        List<Transform> list = m_selectClientGrid.GetChildList();
        List<string> clientList = new List<string>();
        if (list.Count > 0 && m_NameInput.value != "")
        {
            for (int i = 0; i < list.Count; i++)
            {
                //客户端按钮回原位
                m_groupClientGrid.AddChild(list[i]);
                //go.GetComponent<UIDragScrollView>().scrollView = m_groupClientScroll;
                m_selectClientGrid.repositionNow = true;
                m_groupClientGrid.repositionNow = true;
                list[i].GetComponent<GroupClickClientButton>().m_isSelect = false;
                //添加客户端IP
                clientList.Add(list[i].GetComponent<GroupClickClientButton>().m_clientIPLabel.text);
            }
            CloseCreatGroup();
            GameObject ob = NGUITools.AddChild(m_groupGrid.gameObject, m_clientButton);
            ClickClientButton ccb = ob.GetComponent<ClickClientButton>();
            ccb.m_clientIPLabel.text = m_NameInput.value;
            UIEventListener.Get(ccb.gameObject).onClick = ClickGroupClientItem;
            m_clientGroupDic.Add(ob, clientList);
            m_groupGrid.repositionNow = true;
            OpenGroup();
        }
    }

    /// <summary>点击客户端button</summary>
    void ClickGroupClientItem(GameObject go)
    {
        List<string> list = new List<string>();
        if (m_clientGroupDic.TryGetValue(go, out list))
        {
            ClickClientButton ccb = go.GetComponent<ClickClientButton>();
            if (ccb.m_isAdd)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (!m_alreadySelectedCli.Contains(list[i]))
                        m_alreadySelectedCli.Add(list[i]);
                }
            }
            else
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (m_alreadySelectedCli.Contains(list[i]))
                        m_alreadySelectedCli.Remove(list[i]);
                }
            }
        }
    }

    /// <summary>
    /// 设置button碰撞体
    /// </summary>
    /// <param name="bo">是否启用</param>
    void SetButtonCollider(bool bo)
    {
        for (int i = 0; i < m_buttonList.Count; i++)
        {
            m_buttonList[i].GetComponent<Collider>().enabled = bo;
        }
    }

    /// <summary>
    /// 当程序退出时关闭Socket及线程
    /// </summary>
    void OnApplicationQuit()
    {
        //m_client.SendDeletOrder();
        Thread.Sleep(100);
        m_client.CloseNetwork();
    }
}
